package com.hunter.sqlSession;

import com.hunter.config.BoundSql;
import com.hunter.pojo.Configuration;
import com.hunter.pojo.MapperStatement;
import com.hunter.utils.GenericTokenParser;
import com.hunter.utils.ParameterMapping;
import com.hunter.utils.ParameterMappingTokenHandler;
import com.hunter.utils.TokenHandler;
import javafx.geometry.Bounds;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname SimpleExecutor
 * @Description TODO
 * @Date 2021/7/22 23:28
 * @Created by haojie.liao
 */
public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InstantiationException, InvocationTargetException {
        //1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        //2.获取sql语句并转换
        String sql = mapperStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //3.获取预处理对象：preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //4.设置参数

        //4.1获取参数全路径
        String paramterType = mapperStatement.getParamterType();
        Class<?> parameterTypeClass = getClassType(paramterType);
        /*if (parameterTypeClass == null){
            return null;
        }*/
        //#{id}  #{name}  ParameterMapping中存放的是#{}中的值,这个值是与实体对应的,因此通过反射实体取到属性为id、name的值,然后赋值到ParameterMapping中
        //ps：注意，这里的params默认只有一个,如果有多个可以做扩展
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            //反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            //设置参数，从1开始
            preparedStatement.setObject(i+1,o);
        }

        //5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String returnType = mapperStatement.getReturnType();
        Class<?> resultTypeClass = getClassType(returnType);


        ArrayList<Object> objects = new ArrayList<>();;

        //6.封装返回结果集
        while (resultSet.next()){
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object instance = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或内省,根据数据库表和实体的对应关系,完成封装
                PropertyDescriptor propertyDescriptor = null;
                try {
                    propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                }catch (Exception e){
                    continue;
                }
                if (propertyDescriptor != null) {
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(instance, value);
                }
            }
            //添加到集合
            objects.add(instance);
        }

        return (List<E>) objects;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null){
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    /**
     * 完成对#{}的解析工作: 1.将#{}使用?进行代替，
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql){
        //标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{","}",parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql,parameterMappings);
        return boundSql;
    }
}
